/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.*;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;
import logica.ExisteAlquiler;

/**
 *
 * @author Smuggler
 */
public class VistaMantenimiento extends JPanel {

    private Logs logs;
    entities.Alquileres a;
    private static Clientes cliente;
    private List listactualizaTabla;
    ExisteAlquiler existealquiler = new ExisteAlquiler();
    private boolean editando = false;
    public static JFrame frame;
    private Usuarios usuario;

    public VistaMantenimiento(Usuarios usuario) {
        initComponents();
        traerCliente();
        habilitarBotonesBusqueda(true);
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = usuario;
    }

    private Integer getIDMantenimiento(UnidadesAlojamiento idUnidadAlojamiento, Clientes idCliente, Date fechaArribo, Date fechaPartida) {
        Query queryIDMantenimiento;
        Alquileres mantenimiento;
        queryIDMantenimiento = entityManager.createNamedQuery("Alquileres.findByAll");
        queryIDMantenimiento.setParameter("idUnidadAlojamiento", idUnidadAlojamiento);
        queryIDMantenimiento.setParameter("idCliente", idCliente);
        queryIDMantenimiento.setParameter("fechaArribo", fechaArribo);
        queryIDMantenimiento.setParameter("fechaPartida", fechaPartida);
        mantenimiento = (Alquileres) queryIDMantenimiento.getSingleResult();
        return mantenimiento.getIdAlquiler();
    }

    public JFrame getFrame() {
        return frame;
    }

    public void setFrame(JFrame frame) {
        VistaMantenimiento.frame = frame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Alquileres a WHERE (a.tipoAlquiler = 'M' )ORDER BY a.fechaArribo DESC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        unidadesAlojamientoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery.getResultList();
        unidadesAlojamientoQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery1.getResultList();
        clientesQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c  ORDER BY c.apellido");
        clientesList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery.getResultList();
        clientesQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c");
        clientesList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery1.getResultList();
        buttonGroup1 = new javax.swing.ButtonGroup();
        clientesQuery2 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c");
        clientesList2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery2.getResultList();
        buttonGroup2 = new javax.swing.ButtonGroup();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        idUnidadAlojamientoLabel = new javax.swing.JLabel();
        fechaArriboLabel = new javax.swing.JLabel();
        fechaPartidaLabel = new javax.swing.JLabel();
        guardarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        fechaArriboDateChooser = new com.toedter.calendar.JDateChooser();
        fechaPartidaDateChooser = new com.toedter.calendar.JDateChooser();
        unidadAlojamientoComboBox = new javax.swing.JComboBox();
        cancelarButton = new javax.swing.JButton();
        ayudaLabel = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        unidadAlojamientoLabel = new javax.swing.JLabel();
        unidadDepartamentoComboBox = new javax.swing.JComboBox();
        fechaArriboLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        fechaPartidaDateChooser1 = new com.toedter.calendar.JDateChooser();
        fechaArriboDateChooser1 = new com.toedter.calendar.JDateChooser();
        resetButton = new javax.swing.JButton();
        todosCheckBox = new javax.swing.JCheckBox();
        buscarButton = new javax.swing.JButton();
        exportarExcelButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        masterTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idAlquiler}"));
        columnBinding.setColumnName("Codigo Reserva");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idUnidadAlojamiento}"));
        columnBinding.setColumnName("Unidad Alojamiento");
        columnBinding.setColumnClass(entities.UnidadesAlojamiento.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaArribo}"));
        columnBinding.setColumnName("Fecha Inicio");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaPartida}"));
        columnBinding.setColumnName("Fecha Fin");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);

        idUnidadAlojamientoLabel.setText("Unidad Alojamiento:");

        fechaArriboLabel.setText("Fecha Inicio:");

        fechaPartidaLabel.setText("Fecha Fin:");

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        fechaArriboDateChooser.setEnabled(false);

        fechaPartidaDateChooser.setEnabled(false);

        unidadAlojamientoComboBox.setEnabled(false);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, unidadesAlojamientoList, unidadAlojamientoComboBox, "");
        bindingGroup.addBinding(jComboBoxBinding);

        unidadAlojamientoComboBox.addFocusListener(formListener);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        unidadAlojamientoLabel.setText("Unidad de Alojamiento:");

        unidadDepartamentoComboBox.setEnabled(false);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, unidadesAlojamientoList, unidadDepartamentoComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        fechaArriboLabel1.setText("Fecha Inicio:");

        jLabel4.setText("Fecha Fin:");

        fechaPartidaDateChooser1.setEnabled(false);

        fechaArriboDateChooser1.setEnabled(false);

        resetButton.setBackground(new java.awt.Color(1, 154, 210));
        resetButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        resetButton.setForeground(new java.awt.Color(255, 255, 255));
        resetButton.setText("Resetear Busqueda");
        resetButton.setEnabled(false);
        resetButton.addActionListener(formListener);

        todosCheckBox.setText("Todos");
        todosCheckBox.setEnabled(false);
        todosCheckBox.addActionListener(formListener);

        buscarButton.setBackground(new java.awt.Color(1, 154, 210));
        buscarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        buscarButton.setForeground(new java.awt.Color(255, 255, 255));
        buscarButton.setText("Buscar");
        buscarButton.setEnabled(false);
        buscarButton.addActionListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");
        borrarButton.setEnabled(false);
        borrarButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ayudaLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exportarExcelButton)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(nuevoButton)
                                .addGap(3, 3, 3)
                                .addComponent(borrarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(guardarButton))
                            .addComponent(masterScrollPane, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(idUnidadAlojamientoLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(unidadAlojamientoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(65, 65, 65)
                                        .addComponent(fechaArriboLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(fechaArriboDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(fechaPartidaLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(fechaPartidaDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(unidadAlojamientoLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(unidadDepartamentoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(66, 66, 66)
                                        .addComponent(fechaArriboLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(fechaArriboDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(59, 59, 59)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(fechaPartidaDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 257, Short.MAX_VALUE)))
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(250, 250, 250)
                .addComponent(todosCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buscarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resetButton)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fechaArriboLabel)
                            .addComponent(fechaArriboDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(idUnidadAlojamientoLabel)
                            .addComponent(unidadAlojamientoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(fechaPartidaDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fechaPartidaLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(guardarButton)
                    .addComponent(nuevoButton)
                    .addComponent(cancelarButton)
                    .addComponent(borrarButton))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(unidadDepartamentoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(unidadAlojamientoLabel))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fechaArriboLabel1)
                            .addComponent(fechaArriboDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)))
                    .addComponent(fechaPartidaDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(resetButton)
                    .addComponent(buscarButton)
                    .addComponent(todosCheckBox))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ayudaLabel)
                    .addComponent(exportarExcelButton))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.FocusListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                VistaMantenimiento.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                VistaMantenimiento.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                VistaMantenimiento.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == resetButton) {
                VistaMantenimiento.this.resetButtonActionPerformed(evt);
            }
            else if (evt.getSource() == todosCheckBox) {
                VistaMantenimiento.this.todosCheckBoxActionPerformed(evt);
            }
            else if (evt.getSource() == buscarButton) {
                VistaMantenimiento.this.buscarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                VistaMantenimiento.this.exportarExcelButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                VistaMantenimiento.this.borrarButtonActionPerformed(evt);
            }
        }

        public void focusGained(java.awt.event.FocusEvent evt) {
        }

        public void focusLost(java.awt.event.FocusEvent evt) {
            if (evt.getSource() == unidadAlojamientoComboBox) {
                VistaMantenimiento.this.unidadAlojamientoComboBoxFocusLost(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                VistaMantenimiento.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                VistaMantenimiento.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void traerCliente() {
        Query queryExisteUsuario = entityManager.createNamedQuery("Clientes.findByIdCliente").setParameter("idCliente", 1);

        cliente = (Clientes) queryExisteUsuario.getSingleResult();
    }

    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        habilitarBotonesBusqueda(true);
        limpiarBotones();
        limpiarCamposBusqueda();
    }

    private void limpiarBotones() {

        unidadAlojamientoComboBox.setSelectedIndex(-1);

        fechaArriboDateChooser.setDate(null);
        fechaPartidaDateChooser.setDate(null);



    }
    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        habilitarBotones(true);
        habilitarBotonesBusqueda(false);
        editando = false;

    }//GEN-LAST:event_nuevoButtonActionPerformed
    private void nuevoAction() {
        a = new entities.Alquileres();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(a);
        list.add(a);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    }

    private void habilitarBotones(boolean estado) {
        nuevoButton.setEnabled(!estado);
        masterTable.setEnabled(!estado);
        cancelarButton.setEnabled(estado);
        guardarButton.setEnabled(estado);
        unidadAlojamientoComboBox.setEnabled(estado);
        borrarButton.setEnabled(estado);
        fechaArriboDateChooser.setEnabled(estado);
        fechaPartidaDateChooser.setEnabled(estado);

    }

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        int idAlquiler;
        if ((unidadAlojamientoComboBox.getSelectedIndex()) < 0 || (fechaArriboDateChooser.getDate() == null) || (fechaPartidaDateChooser.getDate() == null)) {
            String guardarmensaje = "";

            if (unidadAlojamientoComboBox.getSelectedIndex() < 0) {
                guardarmensaje = guardarmensaje + "                     Unidad Alojamiento:\n";
            }
            if (fechaArriboDateChooser.getDate() == null) {
                guardarmensaje = guardarmensaje + "                     Fecha de Arribo:\n";
            }
            if (fechaPartidaDateChooser.getDate() == null) {
                guardarmensaje = guardarmensaje + "                     Fecha de Partida:\n";
            }
            JOptionPane.showMessageDialog(this, "Seleccione :\n" + guardarmensaje, "Atención", JOptionPane.ERROR_MESSAGE, null);

        } else {

            if (editando) {
                idAlquiler = a.getIdAlquiler();
            } else {
                idAlquiler = 0;
            }
            logs = new Logs();
            logs.setUsuario(usuario);
            int returnExisteAlquiler = existealquiler.verificarAlquilerFecha(fechaArriboDateChooser.getDate(), fechaPartidaDateChooser.getDate(), idAlquiler, (UnidadesAlojamiento) unidadAlojamientoComboBox.getSelectedItem());

            if (returnExisteAlquiler == 0) {

                try {
                    if (!editando) {
                        nuevoAction();
                    }
                    a.setTipoAlquiler("M");
                    a.setMontoReserva(0.0);
                    a.setMontoTotal(0.0);
                    a.setIdCliente(cliente);
                    a.setCantidadPersonas(0);
                    a.setFechaArribo(fechaArriboDateChooser.getDate());
                    a.setFechaPartida(fechaPartidaDateChooser.getDate());
                    a.setIdUnidadAlojamiento((UnidadesAlojamiento) unidadAlojamientoComboBox.getSelectedItem());
                    if (editando) {
                        entityManager.merge(a);
                        editando = false;
                    }

                    if (a.getIdAlquiler() == null) {
                        entityManager.getTransaction().commit();
                        entityManager.getTransaction().begin();
                        Integer idMantenimiento = getIDMantenimiento(a.getIdUnidadAlojamiento(), a.getIdCliente(), a.getFechaArribo(), a.getFechaPartida());
                        logs.setearObservaciones("Alta", "Mantenimiento", idMantenimiento, "VistaMantenimiento");
                    } else {
                        logs.setearObservaciones("Modificación", "Reservas", a.getIdAlquiler(), "VistaMantenimiento");
                    }
                    entityManager.persist(logs);
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                } catch (RollbackException rex) {
                    rex.printStackTrace();
                    entityManager.getTransaction().begin();
                    List<entities.Alquileres> merged = new ArrayList<entities.Alquileres>(list.size());
                    for (entities.Alquileres a : list) {
                        merged.add(entityManager.merge(a));
                    }
                    list.clear();
                    list.addAll(merged);
                }
                habilitarBotones(false);
                refrescar();
                habilitarBotonesBusqueda(true);
                VistaDisponibilidad.resetear(entityManager);
            } else if (returnExisteAlquiler == 2) {
                JOptionPane.showMessageDialog(this, "La Fecha de Inicio no puede ser mayor que la Fecha de Fin ", "Atención", JOptionPane.ERROR_MESSAGE, null);
            } else {
                JOptionPane.showMessageDialog(this, "No se puede cargar la tarea de Mantenimiento, porque se encuentra ocupado", "Atención", JOptionPane.ERROR_MESSAGE, null);
            }
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar();        // TODO add your handling code here:
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        a = list.get(masterTable.getSelectedRow());
        Date fechaArribo = (Date) masterTable.getValueAt(masterTable.getSelectedRow(), 2);
        Date fechaPartida = (Date) masterTable.getValueAt(masterTable.getSelectedRow(), 3);
        UnidadesAlojamiento unidadAlojamiento = (UnidadesAlojamiento) masterTable.getValueAt(masterTable.getSelectedRow(), 1);
        fechaArriboDateChooser.setDate(fechaArribo);
        fechaPartidaDateChooser.setDate(fechaPartida);
        unidadAlojamientoComboBox.setSelectedItem(unidadAlojamiento);
        editando = true;

        habilitarBotonesBusqueda(false);
    }//GEN-LAST:event_masterTableMouseClicked

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar unidades de alojamiento");
    }//GEN-LAST:event_ayudaLabelMouseEntered

    private void unidadAlojamientoComboBoxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_unidadAlojamientoComboBoxFocusLost
    }//GEN-LAST:event_unidadAlojamientoComboBoxFocusLost

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        refrescar();
    }//GEN-LAST:event_resetButtonActionPerformed

    private void todosCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_todosCheckBoxActionPerformed
        if (todosCheckBox.isSelected()) {
            unidadDepartamentoComboBox.setEnabled(false);
        } else {
            unidadDepartamentoComboBox.setEnabled(true);
        }
    }//GEN-LAST:event_todosCheckBoxActionPerformed
    private void actualizaTabla() {

        Query query;

        Date fechaPartida = fechaPartidaDateChooser1.getDate();
        Date fechaArribo = fechaArriboDateChooser1.getDate();

        UnidadesAlojamiento unidadAlojamiento = (UnidadesAlojamiento) unidadDepartamentoComboBox.getSelectedItem();
        Calendar fechaPartidaFinal, fechaArriboInicial;

        if (todosCheckBox.isSelected()) {
            unidadAlojamiento = null;
        }
        if (fechaPartidaDateChooser1.getDate() == null) {
            fechaPartidaFinal = Calendar.getInstance();
            fechaPartidaFinal.set(Calendar.YEAR, 9999);
            fechaPartida = fechaPartidaFinal.getTime();
        }
        if (fechaArriboDateChooser1.getDate() == null) {
            fechaArriboInicial = Calendar.getInstance();
            fechaArriboInicial.set(Calendar.YEAR, 1900);
            fechaArribo = fechaArriboInicial.getTime();
        }

        query = entityManager.createNamedQuery("Alquileres.findByMantenimiento").setParameter("UnidadAlojamiento", unidadAlojamiento).setParameter("fechaFin", fechaPartida).setParameter("fechaInicio", fechaArribo).setParameter("tipoalquiler", "M");



        listactualizaTabla = query.getResultList();

        list.clear();
        list.addAll(listactualizaTabla);
        if (list.isEmpty()) {
            JOptionPane.showMessageDialog(this, "No se encontro ningun resultado, revise los campos de busqueda", "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        }

    }
    private void buscarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarButtonActionPerformed
        habilitarBotonesBusqueda(true);
        actualizaTabla();
    }//GEN-LAST:event_buscarButtonActionPerformed

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Reservas").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed

    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea confirmar el borrado de la tarea de Mantenimiento?", "Borrado de Tarea", JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {
            int[] selected = masterTable.getSelectedRows();
            List<entities.Alquileres> toRemove = new ArrayList<entities.Alquileres>(selected.length);
            for (int idx = 0; idx < selected.length; idx++) {
                entities.Alquileres a = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                toRemove.add(a);
                logs = new Logs();
                logs.setUsuario(usuario);
                logs.setearObservaciones("Borrado", "Mantenimiento", a.getIdAlquiler(), "VistaMantenimiento");
                entityManager.persist(logs);
                entityManager.remove(a);
            }
            list.removeAll(toRemove);
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
            refrescar();
        }
    }//GEN-LAST:event_borrarButtonActionPerformed
    private void habilitarBotonesBusqueda(boolean estado) {

        unidadDepartamentoComboBox.setEnabled(estado);
        fechaArriboDateChooser1.setEnabled(estado);
        fechaPartidaDateChooser1.setEnabled(estado);
        todosCheckBox.setEnabled(estado);
        resetButton.setEnabled(estado);
        buscarButton.setEnabled(estado);

    }

    private void limpiarCamposBusqueda() {
        unidadDepartamentoComboBox.setSelectedIndex(-1);
        fechaArriboDateChooser1.setDate(null);
        fechaPartidaDateChooser1.setDate(null);
        todosCheckBox.setSelected(false);

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton borrarButton;
    private javax.swing.JButton buscarButton;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JButton cancelarButton;
    private java.util.List<entities.Clientes> clientesList;
    private java.util.List<entities.Clientes> clientesList1;
    private java.util.List<entities.Clientes> clientesList2;
    private javax.persistence.Query clientesQuery;
    private javax.persistence.Query clientesQuery1;
    private javax.persistence.Query clientesQuery2;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private com.toedter.calendar.JDateChooser fechaArriboDateChooser;
    private com.toedter.calendar.JDateChooser fechaArriboDateChooser1;
    private javax.swing.JLabel fechaArriboLabel;
    private javax.swing.JLabel fechaArriboLabel1;
    private com.toedter.calendar.JDateChooser fechaPartidaDateChooser;
    private com.toedter.calendar.JDateChooser fechaPartidaDateChooser1;
    private javax.swing.JLabel fechaPartidaLabel;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel idUnidadAlojamientoLabel;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private java.util.List<entities.Alquileres> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton nuevoButton;
    private javax.persistence.Query query;
    private javax.swing.JButton resetButton;
    private javax.swing.JCheckBox todosCheckBox;
    private javax.swing.JComboBox unidadAlojamientoComboBox;
    private javax.swing.JLabel unidadAlojamientoLabel;
    private javax.swing.JComboBox unidadDepartamentoComboBox;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList1;
    private javax.persistence.Query unidadesAlojamientoQuery;
    private javax.persistence.Query unidadesAlojamientoQuery1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        VistaMantenimiento.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new VistaMantenimiento(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Mantenimiento   -   Mantenimiento   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
